<template>
  <div class="ChatSoftware">
    <div class="chatLeft">
      <div class="header">
        <img src="../../static/js/logo.png" alt="">
        页面一
      </div>
      <div class="LeftContent marTop">
        <el-button style="width:80%" type="primary" icon="el-icon-plus" @click="addDialogue">创建新对话</el-button>
      </div>
      <div class="LeftContent marTop">
        课程选择
      </div>
      <div class="LeftContent" style="margin-bottom: 20px">
        <el-select v-model="value" placeholder="请选择" @change="selectChange">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>
      <el-scrollbar style="height:calc(100% - 300px);" ref="scrollbar" wrap-style="overflow-x:hidden;">
        <div :class="item[0].index == ListCheck ? 'currentSession currentCheck' : 'currentSession'"
          :style="Loading ? 'cursor: no-drop;' : ''" v-for="item in List" @click="switchIndex(item[0], Loading)">
          <p>{{ item[0].content }}</p>
          <p>{{ item[0].time }} <i style="font-size:16px" @click.stop="contentDel(item[0], Loading)"
              :style="Loading ? 'cursor: no-drop;' : ''" class="el-icon-delete"></i></p>
        </div>
      </el-scrollbar>
    </div>
    <div class="chatContent">
      <div class="content">
        <el-scrollbar style="height:100%;" ref="scrollbar" wrap-style="overflow-x:hidden;">
          <div class="messageList" ref="messageList" :style="'padding-bottom:' + messagePadding + 'px'">
            <div v-for="(item, index) in List[ListCheck]" :key="item.id" ref="messageLi">
              <div class="user" v-if="item.role == 'user'">
                <div class="userContent">
                  {{ item.content }}
                </div>
                <div class="userImg">
                  <img src="../assets/yonghu.png" alt="">
                </div>
              </div>
              <div class="systemTips" v-if="item.role == 'assistant'">
                <div class="system">
                  <div class="userImg">
                    <img src="../assets/logo.png" alt="">
                  </div>
                  <div class="userContent" v-html="item.StrContent"></div>
                </div>
                <div class="tips">
                  以上内容为 AI 生成，不代表开发者立场，请勿删除或修改本标记
                  <div>
                    <el-tooltip effect="dark" placement="top-start" content="点击可复制">
                      <div class="icon" @click="copyContent(item.content, index)">
                        <i class="el-icon-document-copy"></i>
                      </div>
                    </el-tooltip>
                  </div>
                </div>
              </div>
              <div class="systemTips" v-if="Loading && index + 1 == List[ListCheck].length">
                <div class="system">
                  <div class="userImg">
                    <img src="../assets/logo.png" alt="">
                  </div>
                  <div class="userContent">
                    <i class="el-icon-loading"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>
      <div class="input">
        <el-input placeholder="请输入你的需求。" @keyup.native.enter="sendMessage" v-model="searchInput">
        </el-input>
        <div class="icon" @click="sendMessage">
          <i :class="Loading ? 'el-icon-loading' : 'el-icon-position'"></i>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import MarkdownIt from 'markdown-it'
export default {
  name: '',
  data() {
    return {
      chatUrl: chatUrl,
      searchInput: '你好',
      options: [{
        value: '你作为海军工程大学的教学助理AI你使用你的技能辅助教员进行教学工作包括协助撰写教客，分析学生作业等',
        label: '课程一'
      }],
      value: '你作为海军工程大学的教学助理AI你使用你的技能辅助教员进行教学工作包括协助撰写教客，分析学生作业等',
      List: {},
      ListCheck: '',
      listIndex: 10000,
      Loading: false,
      messagePadding: 0,
      windowHeight: 0,
    }
  },
  mounted() {
    this.windowHeight = window.innerHeight
  },
  methods: {
    selectChange() {
      this.List = {}
      this.ListCheck = ''
      this.listIndex = 10000
    },
    addDialogue() {
      if (this.Loading) {
        this.$message.warning('当前对话生成中！')
        return false;
      }
      if (this.ListCheck == '') {
        this.$message.warning('已切换最新会话！')
        return false;
      }
      this.ListCheck = ''
    },
    switchIndex(item) {
      if (this.Loading) return false;
      this.ListCheck = item.index
      this.messagePadding = item.messagePadding
      setTimeout(() => {
        this.toScrollTop(item.toScrollTopPX)
      }, 0);
    },
    sendMessage() {
      if (this.Loading) return false;
      if (!this.searchInput || this.searchInput == '') {
        this.$message.warning('发送内容不能为空！')
        return false
      };
      if (this.searchInput.trim() == '') {
        this.$message.warning('发送内容不能为空！')
        return false;
      }
      let listIndex = this.ListCheck ? this.ListCheck : this.listIndex
      this.ListCheck ? null : this.listIndex--;
      let time = this.currentTime()
      let obj = {
        role: 'user',
        content: this.searchInput,
        time: time,
        index: listIndex
      }
      if (this.ListCheck == '') {
        this.List[listIndex] = []
        this.ListCheck = listIndex
      }
      this.List[listIndex].push(obj)
      this.Loading = true
      this.searchInput = ''
      this.CalculateHeight(true)
      this.axios.post(this.chatUrl + '/chat/completions',
        {
          model: "chatglm2-6b",
          messages: [{
            "role": "system",
            "content": this.value,
          }, ...this.List[listIndex]],
        },
        {
          headers: {
            'Authorization': 'Bearer none',
            'Content-Type': 'application/json'
          }
        }).then(res => {
          this.Loading = false
          let content = res.data.choices[0].message
          const md = new MarkdownIt()
          content.StrContent = md.render(content.content)
          this.List[listIndex].push(content)
          this.CalculateHeight(false)
        }).catch(() => {
          this.Loading = false
          this.$message.error('服务器错误，请稍后重试。')
        })
    },
    toScrollTop(number) {
      const el = this.$refs['scrollbar'].wrap;
      el.scrollTop = number;
    },
    copyContent(item, index) {
      const save = function (e) {
        e.clipboardData.setData('text/plain', item)
        e.preventDefault() // 阻止默认行为
      }
      document.addEventListener('copy', save) // 添加一个copy事件
      document.execCommand('copy')
      this.$message.success('复制成功。')
    },
    contentDel(item) {
      if (this.Loading) return false;
      delete this.List[item.index]
      this.ListCheck = ''
      this.$message.success('删除成功。')
    },
    currentTime() {
      var date = new Date();
      var year = date.getFullYear(); //月份从0~11，所以加一
      let month = date.getMonth();
      var dateArr = [
        date.getMonth() + 1,
        date.getDate(),
        date.getHours(),
        date.getMinutes(),
        date.getSeconds(),
      ];
      //如果格式是MM则需要此步骤，如果是M格式则此循环注释掉
      for (var i = 0; i < dateArr.length; i++) {
        if (dateArr[i] >= 1 && dateArr[i] <= 9) {
          dateArr[i] = "0" + dateArr[i];
        }
      }
      var strDate =
        year +
        "/" +
        dateArr[0] +
        "/" +
        dateArr[1] +
        " " +
        dateArr[2] +
        ":" +
        dateArr[3] +
        ":" +
        dateArr[4];
      //此处可以拿外部的变量接收  strDate:2022-05-01 13:25:30
      //this.date = strDate;
      return strDate
    },
    CalculateHeight(bool) {
      let height = this.windowHeight - 110
      if (bool) {
        setTimeout(() => {
          let messageListPX = this.$refs.messageList.offsetHeight - this.messagePadding
          let LoadingHeight = this.$refs.messageLi[this.$refs.messageLi.length - 1].offsetHeight
          let maxHeight = height - LoadingHeight
          let toScrollTopPX = messageListPX - LoadingHeight
          this.messagePadding = (height - messageListPX) > 0 ?
            (height - messageListPX) : 0
          this.List[this.ListCheck].length > 2 ? this.messagePadding += toScrollTopPX : null
          this.messagePadding > maxHeight ? this.messagePadding = maxHeight : null
          this.List[this.ListCheck][0].messagePadding = this.messagePadding
          setTimeout(() => {
            this.toScrollTop(toScrollTopPX)
            this.List[this.ListCheck][0].toScrollTopPX = toScrollTopPX
          }, 0);
        }, 0);
      } else {
        setTimeout(() => {
          let liHeight = this.$refs.messageLi[this.$refs.messageLi.length - 1].offsetHeight +
            this.$refs.messageLi[this.$refs.messageLi.length - 2].offsetHeight
          this.messagePadding = (height - liHeight) > 0 ? (height - liHeight) : 0
          this.List[this.ListCheck][0].messagePadding = this.messagePadding
          setTimeout(() => {
            this.toScrollTop(this.$refs.messageList.offsetHeight)
            this.List[this.ListCheck][0].toScrollTopPX = this.$refs.messageList.offsetHeight
          }, 0);
        }, 0);
      }
    },
  }
}

</script>
<style lang="scss" scoped>
.messageList {
  overflow: hidden;
}

.content>>>.el-scrollbar__bar {
  display: none;
}

.chatContent>>>.el-input__inner {
  height: 60px !important;
  border-radius: 10px !important;
  padding: 0 55px 0 15px !important;
}

.ChatSoftware {
  display: flex;
  justify-content: space-between;
  background-color: #f6f7f9;
  height: 100vh;

  .chatContent {
    width: calc(100% - 260px);
    height: 100%;
    text-align: center;

    .content {
      width: 810px;
      margin: 0 auto;
      height: calc(100% - 110px);
      font-size: 15px;
      text-align: left;
      line-height: 30px;

      .user,
      .system {
        display: flex;
        justify-content: right;
        padding: 20px;

        .userContent {
          max-width: 720px;
        }

        .userImg {
          width: 35px;
          height: 35px;
          margin-left: 10px;
          border-radius: 35px;

          img {
            height: 100%;
            width: 100%;
          }
        }
      }

      .systemTips {
        background-color: #ffffff;
        border-radius: 8px;
        padding-bottom: 20px;

        .tips {
          padding: 0 20px 0 65px;
          font-size: 14px;
          color: #b0b7c0;
          display: flex;
          align-items: center;
          justify-content: space-between;

          .icon {
            height: 40px;
            width: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;

            &:hover {
              background-color: #f2f5ff;
              color: #409eff;
              border-radius: 8px;
            }
          }
        }
      }

      .system {
        justify-content: left;
        background-color: #ffffff;
        padding-bottom: 0;

        .userImg {
          margin-left: 0px;
          margin-right: 10px;
        }
      }
    }

    .input {
      width: 810px;
      margin: 0 auto;
      height: 100px;
      padding-bottom: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;

      .icon {
        position: absolute;
        height: 40px;
        width: 40px;
        background-color: #f2f5ff;
        right: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 20px;
        cursor: pointer;

        &:hover {
          background-color: #e4eaff;
          color: #409eff;
        }
      }
    }
  }

  .chatLeft {
    width: 259px;
    background-color: #ffffff;
    height: 100%;
    border-right: 1px solid #d7d7d7;

    .header {
      padding: 10px 0;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: bold;

      img {
        height: 40px;
        width: 40px;
        margin-right: 10px;
      }
    }

    .marTop {
      margin-top: 30px;
    }

    .LeftContent {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 40px;
    }

    .currentSession {
      padding: 20px;
      font-size: 12px;
      height: 40px;
      border-left: 3px solid #ffffff;
      cursor: pointer;

      p {
        height: 20px;
        line-height: 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        i:hover {
          cursor: pointer;
          color: red;
        }
      }
    }

    .currentCheck {
      border-left: 3px solid #3e6ffb;
      background-color: #f8f8f8;
    }
  }
}
</style>